package com.itheima.filter;
import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
* 过滤页面的
* */
//指定拦截的路基
@Slf4j
@WebFilter(filterName ="pageFilter",urlPatterns = "/*")
public class pageFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //请求和响应需要强转
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次访问的url
        String uri = request.getRequestURI();
        //log.info(uri);

        //所有需要放行的页面
        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg"
        };

        //判断是否符合这个路径
        Boolean flag = checkURI(uri,loginUrls);

        if (flag){
            //包含，则放行
            filterChain.doFilter(request,response);
            //结束方法
            return;
        }

        //判断管理端用户是否登录
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null){
            //放到线程中
            BaseContext.setCurrentId(employee);
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //判断客户端的用户是否登录
        Long user = (Long) request.getSession().getAttribute("user");
        if (user != null){
            //放到线程中
            BaseContext.setCurrentId(user);
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    private Boolean checkURI(String uri, String[] loginUrls) {
        for (String url : loginUrls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
